﻿using DotNetMVC.OA.DALFactory;
using DotNetMVC.OA.IDAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace DotNetMVC.OA.BLL
{
    public abstract class BaseService<T> where T : class, new()
    {
        public IBaseDal<T> CurrentDal { get; set; }
        public IDbSession DbSession
        {
            get { return DbSessionFactory.GetCurrentDbSession(); }
        }

        public BaseService()
        {
            //目的：CurrentDal 使用之前，初始化赋值
            SetCurrentDal();
        }

        /// <summary>
        /// 抽象方法，要求子类必须实现
        /// 目的：逼迫子类 CurrentDal 赋值
        /// </summary>
        public abstract void SetCurrentDal();

        //crue
        #region 查询
        public IQueryable<T> GetEntities(Expression<Func<T, bool>> whereLambda)
        {
            return CurrentDal.GetEntities(whereLambda);
        }

        public IQueryable<T> GetPageEntities<S>(
           int pageSize, int pageIndex, out int total,
           Expression<Func<T, bool>> whereLambda,
           Expression<Func<T, S>> orderByLambda,
           bool isAsc
           )
        {
            return CurrentDal.GetPageEntities<S>(pageSize, pageIndex, out total, whereLambda, orderByLambda, isAsc);
        }
        #endregion

        #region cud
        public T Add(T Entity)
        {
            CurrentDal.Add(Entity);
            DbSession.SaveChanges();
            return Entity;
        }
        public bool Update(T Entity)
        {
            CurrentDal.Update(Entity);
            return DbSession.SaveChanges() > 0;
        }
        public bool Delete(T Entity)
        {
            CurrentDal.Delete(Entity);
            return DbSession.SaveChanges() > 0;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="isBatch">是否批量处理，默认 false</param>
        /// <returns></returns>
        public bool Delete(long id,bool isBatch=false)
        {
            CurrentDal.Delete(id);
            if (isBatch)
            {
                return true;
            }
            return DbSession.SaveChanges() > 0;
        }

        public int Delete(List<long> ids)
        {
            foreach (long id in ids)
            {
                Delete(id,true);
            }
            return DbSession.SaveChanges();
        }
        #endregion
    }
}
